package com.nq.common.calculator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nq.dao.FundsApplyMapper;
import com.nq.dao.UserMapper;
import com.nq.dao.UserPendingorderMapper;
import com.nq.pojo.FundsApply;
import com.nq.pojo.User;
import com.nq.pojo.UserPendingorder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

/**
 * 用户资金计算器
 */
@Component
@Slf4j
public class UserFundsCalculator {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserPendingorderMapper userPendingorderMapper;
    @Autowired
    FundsApplyMapper fundsApplyMapper;
    
    /**
     * 计算挂单冻结金额
     * @return
     */
    public BigDecimal calculateHangingSlipFrozenAmount(Integer userId){
        BigDecimal allFreezeAssets = new BigDecimal(BigInteger.ZERO);
        // 冻结 - 挂单冻结
        QueryWrapper<UserPendingorder> pendingorderQueryWrapper = new QueryWrapper<>();
        pendingorderQueryWrapper.eq("user_id", userId);
        pendingorderQueryWrapper.eq("status", 0);
        List<UserPendingorder> userPendingorders = userPendingorderMapper.selectList(pendingorderQueryWrapper);
        for (UserPendingorder pendingorder : userPendingorders) {
            Integer buyNum = pendingorder.getBuyNum();
            BigDecimal nowPrice = pendingorder.getNowPrice();

            BigDecimal freezeAssets = new BigDecimal(buyNum).multiply(nowPrice);
            allFreezeAssets = allFreezeAssets.add(freezeAssets);
        }
        return allFreezeAssets;
    }

    /**
     * 计算配资保证金冻结金额
     * @return
     */
    public BigDecimal calculateDepositFrozenAmount(Integer userId){

        BigDecimal allFreezeAssets = new BigDecimal(BigInteger.ZERO);
        // 冻结 - 加上配资保证金
        List<FundsApply> fundsApplyList = fundsApplyMapper.getUserEnabledSubaccount(userId);
        for (FundsApply fundsApply : fundsApplyList) {
            // 保证金
            allFreezeAssets = allFreezeAssets.add(fundsApply.getMargin());

        }
        return allFreezeAssets;
    }

    /**
     * 计算新股收购冻结金额
     * @return
     */
    public BigDecimal calculateNewShareAcquisitionsFrozenAmount(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if (null == user) {
            return new BigDecimal(BigInteger.ZERO);
        }
        BigDecimal djzj = user.getDjzj();
        return djzj;

    }
}
